package com.dt.common.validation.parser;

import java.lang.reflect.Field;
import java.math.BigDecimal;

import com.alibaba.fastjson.JSONObject;
import com.dt.common.validation.annotation.DecimalMin;
import com.dt.common.validation.definition.DecimalMinDefinition;
import com.dt.common.validation.exception.BuildingException;
import com.dt.common.validation.impl.DefaultValidationDefinition;
import com.dt.common.validation.itf.PropertyGetter;

public class DecimalMinDefinitionParser extends DefinitionParser {

	@Override
	public DefaultValidationDefinition parseFromAnnotation(Field field, PropertyGetter propertyGetter) {
		DecimalMin decimalMin = field.getAnnotation(DecimalMin.class);
		if (decimalMin != null) {
			DecimalMinDefinition definition = new DecimalMinDefinition();
			definition.setMinValue(new BigDecimal(decimalMin.value()));
			definition.setInclusive(decimalMin.inclusive());
			definition.setRawMsg(decimalMin.msg());

			return definition;
		}
		return null;
	}

	@Override
	public DefaultValidationDefinition parseFromJson(JSONObject metaValues) {
		BigDecimal value = metaValues.getBigDecimal("value");
		if (value == null) {
			throw new BuildingException("DecimalMin value must defined.");
		}
		Boolean inclusive = metaValues.getBoolean("inclusive");
		inclusive = inclusive == null ? Boolean.TRUE : inclusive;

		DecimalMinDefinition definition = new DecimalMinDefinition();
		definition.setMinValue(value);
		definition.setInclusive(inclusive);
		definition.setRawMsg(this.getMsgDefinition(metaValues, true));

		return definition;
	}

}
